package com.ahrhyj.common.config;

import cn.hutool.core.util.StrUtil;
import com.ahrhyj.common.utils.MimeTypeUtils;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class FastDFSClient {
    private final Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    /**
     * 上传文件
     *
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResAccessUrl(storePath);
    }

    /**
     * 上传文件
     *
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        StorePath storePath = storageClient.uploadFile(inputStream, file.length(), FilenameUtils.getExtension(file.getName()), null);
        return getResAccessUrl(storePath);
    }

    /**
     * 将一段字符串生成一个文件上传
     *
     * @param content       文件内容
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null);
        return getResAccessUrl(storePath);
    }

    // 封装图片完整URL地址
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        return fileUrl;
    }

    /**
     * 下载文件,返回字节数组
     *
     * @param fileUrl 文件url
     * @return
     */
    public byte[] downloadByte(String fileUrl) {
        ConcurrentHashMap<String, String> pathMap = getPath(fileUrl);
        String groupName = pathMap.get("groupName");
        String filePath = pathMap.get("filePath");
        byte[] bytes = storageClient.downloadFile(groupName, filePath, new DownloadByteArray());
        return bytes;
    }

    /**
     * 下载文件，返回InputStream
     *
     * @param fileUrl 文件url
     * @return
     */
    public InputStream downloadInputStream(String fileUrl) {
        ConcurrentHashMap<String, String> pathMap = getPath(fileUrl);
        String groupName = pathMap.get("groupName");
        String filePath = pathMap.get("filePath");
        InputStream ins = storageClient.downloadFile(groupName, filePath, new DownloadCallback<InputStream>() {
            @Override
            public InputStream recv(InputStream ins) throws IOException {
                // 将此ins返回给上面的ins
                return ins;
            }
        });
        return ins;

    }

    /**
     * 下载文件，返回文件
     *
     * @param fileUrl 文件url
     * @return
     */
    public void downloadFile(String fileUrl, HttpServletRequest request, HttpServletResponse response) {
        try {
            ConcurrentHashMap<String, String> pathMap = getPath(fileUrl);
            String groupName = pathMap.get("groupName");
            String filePath = pathMap.get("filePath");
            String fileName = pathMap.get("fileName");
            InputStream input = storageClient.downloadFile(groupName, filePath, new DownloadCallback<InputStream>() {
                @Override
                public InputStream recv(InputStream input) throws IOException {
                    // 将此input返回给上面的input
                    return input;
                }
            });

            //根据文件名获取 MIME 类型
            System.out.println("fileName :" + fileName); // wKgAKF15nkOAdYczAACrr9cLDU4592.jpg
            String contentType = request.getServletContext().getMimeType(fileName);
            if (StrUtil.isBlank(contentType)) {
                contentType = MimeTypeUtils.getType(fileName);
            }
            String contentDisposition = "attachment;filename=" + fileName;

            // 设置头
            response.setHeader("Content-Type", contentType);
            response.setHeader("Content-Disposition", contentDisposition);

            // 获取绑定了客户端的流
            ServletOutputStream output = response.getOutputStream();

            // 把输入流中的数据写入到输出流中

            IOUtils.copy(input, output);
            input.close();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

    /**
     * 下载文件，返回文件
     *
     * @param fileUrl 文件url
     * @return
     */
    public void downloadFile(String fileUrl, String downFileName, HttpServletRequest request, HttpServletResponse response) {
        try {
            ConcurrentHashMap<String, String> pathMap = getPath(fileUrl);
            String groupName = pathMap.get("groupName");
            String filePath = pathMap.get("filePath");
            String fileName = pathMap.get("fileName");
            InputStream input = storageClient.downloadFile(groupName, filePath, new DownloadCallback<InputStream>() {
                @Override
                public InputStream recv(InputStream input) throws IOException {
                    // 将此input返回给上面的input
                    return input;
                }
            });
            fileName = StringUtils.isNotBlank(downFileName) ? downFileName : fileName;
            //根据文件名获取 MIME 类型
            System.out.println("fileName :" + fileName); // wKgAKF15nkOAdYczAACrr9cLDU4592.jpg
            String contentType = request.getServletContext().getMimeType(fileName);
            if (StrUtil.isBlank(contentType)) {
                contentType = MimeTypeUtils.getType(fileName);
            }
            String contentDisposition = "attachment;filename=" + fileName;

            // 设置头
            response.setHeader("Content-Type", contentType);
            response.setHeader("Content-Disposition", contentDisposition);

            // 获取绑定了客户端的流
            ServletOutputStream output = response.getOutputStream();

            // 把输入流中的数据写入到输出流中

            IOUtils.copy(input, output);
            input.close();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

    /**
     * 删除文件
     *
     * @param fileUrl 文件访问地址
     * @return
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            logger.warn(e.getMessage());
        }
    }

    /**
     * @Description: 将传过来的url切割成需要的url
     * @Author: yelei
     * @Date: 2019/9/12
     */
    public static ConcurrentHashMap<String, String> getPath(String fileUrl) {
        ConcurrentHashMap<String, String> pathMap = new ConcurrentHashMap<>();
        String groupName = fileUrl.substring(fileUrl.indexOf("g"), fileUrl.indexOf("M") - 1);
        String filePath = fileUrl.substring(fileUrl.indexOf("M"));
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        pathMap.put("groupName", groupName);
        pathMap.put("filePath", filePath);
        pathMap.put("fileName", fileName);
        return pathMap;
    }
}